package com.alm.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alm.common.auth.ActiveCodeDTO;
import com.alm.common.auth.CipherInfo;
import com.alm.common.utils.AuthUtil;
import com.alm.common.utils.file.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.alm.common.constant.Constants;
import com.alm.common.core.domain.AjaxResult;
import com.alm.common.core.domain.entity.SysMenu;
import com.alm.common.core.domain.entity.SysUser;
import com.alm.common.core.domain.model.LoginBody;
import com.alm.common.utils.SecurityUtils;
import com.alm.framework.framework.web.service.SysLoginService;
import com.alm.framework.framework.web.service.SysPermissionService;
import com.alm.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 激活
     * @return
     */
    @PostMapping("/activation")
    public AjaxResult activation(@RequestBody ActiveCodeDTO dto) {
        if(StringUtils.isBlank(dto.getActCode())) {
            return AjaxResult.error("激活码不可为空");
        }

        Boolean flag = AuthUtil.validateActivationCode(dto);
        return flag ? AjaxResult.success() : AjaxResult.error("激活码不正确");
    }

    /**
     * 授权校验
     * @return
     */
    @GetMapping("/auth")
    public AjaxResult auth() {
        Map<String, Object> map = new HashMap<>(4);

        // 获取授权码
        String ac = FileUtils.readFileByPath(AuthUtil.AUTH_FILE_PATH + AuthUtil.AUTH_FILE_PATH_NAME);
        CipherInfo cipherInfo = AuthUtil.getPlaintextObjForLogin();
        Boolean auth = AuthUtil.validateAuth(ac, cipherInfo);
//        cipherInfo.setExpiredTime("2024-08-01");
        Boolean expiration = AuthUtil.validateTimeExpiration(cipherInfo.getExpiredTime());
        Boolean timeFlag = AuthUtil.validateTimeIsBefore(cipherInfo.getExpiredTime());
        // 返回激活码
        if(FileUtils.isExists(AuthUtil.SECRET_FILE_PATH + AuthUtil.SECRET_FILE_PATH_NAME)) {
            String secretInfo = FileUtils.readFileByPath(AuthUtil.SECRET_FILE_PATH + AuthUtil.SECRET_FILE_PATH_NAME);
            map.put("actCode", secretInfo);
        }
        // 校验
        if(auth && !expiration){
            // 如果即将过期
            if(timeFlag) {
                String info = AuthUtil.generatorInfo();
                map.put("code", info);
                map.put("tip", "系统使用权限即将过期，将于" + cipherInfo.getExpiredTime() + "无法使用，请尽快联系管理员");
            }
            map.put("flag", "Y");
        }else {
            String info = AuthUtil.generatorInfo();
            map.put("code", info);
            map.put("flag", "N");
            map.put("msg", "授权校验未通过， 请联系管理员");
        }

        // 为Y默认通过
//        map.put("flag", "Y");
        return AjaxResult.success(map);
    }

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        // 获取授权码
//        String ac = FileUtils.readFileByPath(AuthUtil.AUTH_FILE_PATH + AuthUtil.AUTH_FILE_PATH_NAME);
//        CipherInfo cipherInfo = AuthUtil.getPlaintextObjForLogin();
//        Boolean auth = AuthUtil.validateAuth(ac, cipherInfo);
//        Boolean expiration = AuthUtil.validateTimeExpiration(cipherInfo.getExpiredTime());
//        Boolean timeFlag = AuthUtil.validateTimeIsBefore(cipherInfo.getExpiredTime());
//        String msg = "";
//        if(auth && !expiration && timeFlag){
//            msg = "系统使用权限即将过期，将于" + cipherInfo.getExpiredTime() + "无法使用，请尽快联系管理员";
//        }

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
//        Long userId = SecurityUtils.getUserId();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
